package com.baizhi.Controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.baizhi.entity.Admin;
import com.baizhi.service.AdminService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @RequestMapping("getCode")
    public void getCode(HttpServletResponse response, HttpSession session) throws IOException {
        //定义图形验证码的长和宽
        LineCaptcha  lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        //把获得验证码存入session方便登录的时候做判断
        session.setAttribute("lineCaptcha",lineCaptcha);
        //把获取的验证码响应到页面
        lineCaptcha.write(response.getOutputStream());
    }
    @RequestMapping("login")
    public String login(HttpSession session,String code,String name,String password){
        Logger logger= LoggerFactory.getLogger(Admin.class);
        //验证图形验证码的有效性，返回boolean值
       LineCaptcha lineCaptcha= (LineCaptcha) session.getAttribute("lineCaptcha");
        //System.out.println(lineCaptcha+"======================lineCaptcha");
        logger.debug(lineCaptcha+"======================lineCaptcha");
        boolean verify=lineCaptcha.verify(code);
        System.out.println(verify+"---------------------");
        Admin admin=null;
        if(verify) {
            admin = adminService.login(name, password);
            //System.out.println(admin+"===============admin");
            logger.debug(admin+"===============admin");
        }
       if(admin!=null) {
           session.setAttribute("admin",admin);
           return "main";
       }else{
           return "redirect:/login.jsp";
       }
    }
}
